package com.eye.catcher.service.generate.impl;

import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eye.catcher.constants.RedisConstants;
import com.eye.catcher.entity.TYwDaBaseInfo;
import com.eye.catcher.service.generate.*;
import com.eye.catcher.system.user.param.*;
import com.eye.catcher.system.yw.Info.param.BaseInfoDto;
import com.eye.catcher.system.yw.Info.param.BaseInfoPage;
import com.eye.catcher.utils.DownloadUtils;
import com.eye.catcher.utils.MD5EncryptUtils;
import com.eye.catcher.utils.RandomIdUtils;
import com.eye.catcher.common.RedisUtils;
import com.eye.catcher.constants.SbCode;
import com.eye.catcher.entity.TSysDaUser;
import com.eye.catcher.mapper.TSysDaUserMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eye.catcher.system.module.param.ModuleDto;
import com.eye.catcher.system.role.param.RoleDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author huzhiwei
 * @since 2022-02-08
 */
@Slf4j
@Service
public class TSysDaUserServiceImpl extends ServiceImpl<TSysDaUserMapper, TSysDaUser> implements ITSysDaUserService {

    @Autowired
    private ITSysDaModuleService moduleService;
    @Autowired
    private ITSysDaRoleService roleService;
    @Autowired
    private ITSysDaUserRoleService userRoleService;
    @Autowired
    private ITYwDaBaseInfoService baseInfoService;
    @Autowired
    private TSysDaUserMapper userMapper;
    @Autowired
    private RedisUtils redisUtils;

    @Value("${download.template.url-path}")
    private String downloadTemplateUrlPath;

    @Override
    public UserLoginResponse login(UserLoginRequst requst) {
        UserLoginResponse res = new UserLoginResponse();
        res.setUserId("0");
        res.setCode(SbCode.USERORPASSWORD_ERRROR.getCode());
        res.setMsg(SbCode.USERORPASSWORD_ERRROR.getMessage());

        try {
            QueryWrapper<TSysDaUser> wrapper = Wrappers.query();
            wrapper.eq("LOGIN_NAME",requst.getUsername());
            TSysDaUser sysUser = this.getOne(wrapper);
//            System.out.println(user);
            if (sysUser != null) {
                String md5Password = MD5EncryptUtils.MD5Encode(requst.getPassword());
                System.out.println(md5Password);
                if (sysUser.getPassword().equals(md5Password)) {
                    res.setUserId(sysUser.getId());
                    res.setUserName(sysUser.getUserName());
                    res.setLoginName(sysUser.getLoginName());
                    res.setCode(SbCode.SUCCESS.getCode());
                    res.setMsg(SbCode.SUCCESS.getMessage());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("login:",e);
            return res;
            // 这里在auth那里设置了异常
        }
        return res;
    }

    @Override
    public UserLoginInfo getUserInfoById(String userId, String getUserInfoType) {
        UserLoginInfo res = new UserLoginInfo();

        UserDto userDto = null;
        List<RoleDto> roleList = null;
        List<ModuleDto> moduleList = null;
        try{
            if(SbCode.GETUSERINFOBYID_TYPE_All.getCode().equals(getUserInfoType)
                || SbCode.GETUSERINFOBYID_TYPE_NOT_MODULE.getCode().equals(getUserInfoType)
            ){
                //获取用户
                userDto = userMapper.getUserInfoById(userId);
                //获取角色
                roleList = roleService.getRoleByUserId(userId);
            }
            if(SbCode.GETUSERINFOBYID_TYPE_All.getCode().equals(getUserInfoType)
                    || SbCode.GETUSERINFOBYID_TYPE_ONLAY_MODULE.getCode().equals(getUserInfoType))
            {
                //获取模块
                if(null != userDto && "admin".equals(userDto.getLoginName())){
                    moduleList = (List<ModuleDto>)moduleService.getAdminModuleList();
                }else{
                    moduleList = moduleService.getModuleByUserId(userId);
                }
                moduleList = moduleService.reorderModuleDto(moduleList);
            }
            res = UserLoginInfo.builder()
                    .userDto(userDto)
                    .moduleDtoList(moduleList)
                    .roleDtoList(roleList)
                    .build();
            res.setCode(SbCode.SUCCESS.getCode());
            res.setMsg(SbCode.SUCCESS.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            log.error("getUserInfoById:",e);
            res.setCode(SbCode.SYSTEM_ERROR.getCode());
            res.setMsg(SbCode.SYSTEM_ERROR.getMessage());
        }
        return res;
    }

    @Override
    public void addUser(TSysDaUser user,String userId) {
        String id = RandomIdUtils.getGuid();
        user.setId(id);
        if(StringUtils.isNotEmpty(user.getPassword())) {
            user.setPassword(MD5EncryptUtils.MD5Encode(user.getPassword()));
        }else{
            //默认密码
            user.setPassword(MD5EncryptUtils.MD5Encode("123456"));
        }
        user.setCreateTime(LocalDateTime.now());
        user.setCreateUserId(userId);
        user.setCreateYear(LocalDateTime.now().getYear());
        user.setSource(SbCode.DATA_SOURCE_CREATE.getCode());

        if(null != user.getBaseId()){
            TYwDaBaseInfo baseInfo = baseInfoService.getById(user.getBaseId());
            if(null != baseInfo) {
                user.setBaseId(baseInfo.getId());
                user.setBaseCode(baseInfo.getBaseCode());
                user.setBaseName(baseInfo.getBaseName());
            }
        }
        if(StringUtils.isNotEmpty(user.getBaseCode())){
            TYwDaBaseInfo baseInfo = (TYwDaBaseInfo)baseInfoService.getBaseInfoByCode(user.getBaseCode());
            if(null != baseInfo) {
                user.setBaseId(baseInfo.getId());
                user.setBaseCode(baseInfo.getBaseCode());
                user.setBaseName(baseInfo.getBaseName());
            }
        }
        this.save(user);
    }
    @Override
    public void editUser(TSysDaUser user,String userId) {
        TSysDaUser oldUser = this.getById(userId);
        QueryWrapper<TSysDaUser> wrapper = Wrappers.query();
        wrapper.eq("ID",user.getId());
        if(StringUtils.isNotEmpty(user.getPassword())){
            user.setPassword(MD5EncryptUtils.MD5Encode(user.getPassword()));
            user.setPrevPassword(oldUser.getPassword());
        }
        user.setUpdateTime(LocalDateTime.now());
        user.setUpdateUserId(userId);
        if(null !=user.getBaseId()){
            TYwDaBaseInfo baseInfo = baseInfoService.getById(user.getBaseId());
            if(null != baseInfo) {
                user.setBaseId(baseInfo.getId());
                user.setBaseCode(baseInfo.getBaseCode());
                user.setBaseName(baseInfo.getBaseName());
            }
        }
        if(StringUtils.isNotEmpty(user.getBaseCode())){
            TYwDaBaseInfo baseInfo = (TYwDaBaseInfo)baseInfoService.getBaseInfoByCode(user.getBaseCode());
            if(null != baseInfo) {
                user.setBaseId(baseInfo.getId());
                user.setBaseCode(baseInfo.getBaseCode());
                user.setBaseName(baseInfo.getBaseName());
            }
        }
        this.update(user,wrapper);
    }
    @Override
    public void editUserPassword(String userIds,String password,String userId) {
        QueryWrapper<TSysDaUser> wrapper = Wrappers.query();
        wrapper.in("ID",Arrays.asList(userIds.split(",")));
        List<TSysDaUser> list = this.list(wrapper);
        List<TSysDaUser> updateBatchList = new ArrayList<>();
        for(TSysDaUser user : list){
            user.setPrevPassword(user.getPassword());
            user.setPassword(MD5EncryptUtils.MD5Encode(password));
            user.setUpdateTime(LocalDateTime.now());
            user.setUpdateUserId(userId);
            updateBatchList.add(user);
        }
        if(updateBatchList.size() > 0 ){
            this.updateBatchById(updateBatchList);
        }
    }

    @Override
    public String exportUserTemplate(HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException {
        String urlPath = downloadTemplateUrlPath + "/template";
        String fileName = "用户导入模板.xlsx";
        InputStream inputStream = new FileInputStream(urlPath+"/"+fileName);
        DownloadUtils.downloadFile(request, response, inputStream, fileName);

        return null;
    }

    @Override
    public String uploadUserTemplate(MultipartFile file,String userId) throws IOException {
//        UserLoginInfo userLoginInfo = (UserLoginInfo)redisUtils.get(RedisConstants.USER_INFO_EXPIRE.getKey()+userId);
        List<TSysDaUser> userList = new ArrayList<>();
        ExcelUtil.readBySax(file.getInputStream(), 0, (sheetIndex, rowIndex, list) -> {
            if((null == list || list.size() != 9) || sheetIndex != 0 || rowIndex == 0){
                return;
            }
//            System.out.println(sheetIndex); // 输出第几张表格 从0开始
//            System.out.println(rowIndex); // 输出第几行数据 从0开始 第一行一般为表头
            System.out.println(list); // 每行的数据 封装在一个列表里面
            String baseCode = this.getStringParam(list.get(8));
            TYwDaBaseInfo baseInfo = null;
            if(StringUtils.isNotEmpty(baseCode)){
                baseInfo = (TYwDaBaseInfo)baseInfoService.getBaseInfoByCode(baseCode);
            }
            userList.add(
                new TSysDaUser(
                    RandomIdUtils.getGuid(),
                    this.getStringParam(list.get(0)),
                    this.getStringParam(list.get(1)),
                    MD5EncryptUtils.MD5Encode("123456"),
                    this.getStringParam(list.get(2)),
                    LocalDateTime.now().getYear(),
                    userId,
                    LocalDateTime.now(),
                    "1",
                    this.getStringParam(list.get(3)),
                    this.getStringParam(list.get(4)),
                    this.getStringParam(list.get(5)),
                    this.getStringParam(list.get(6)),
                    SbCode.DATA_SOURCE_IMPORT.getCode(),
                    SbCode.DATA_NORMAL.getCode(),
                    this.getStringParam(list.get(7)),
                    (null!=baseInfo)?baseInfo.getId():null,
                    (null!=baseInfo)?baseInfo.getBaseCode():baseCode,
                    (null!=baseInfo)?baseInfo.getBaseName():null
                )
            );
        });
        if(userList.size() > 0){
            this.saveBatch(userList);
        }
        return null;
    }
    private String getStringParam(Object o) {
        if(null == o){
            return null;
        }
        if(StringUtils.isNotEmpty(String.valueOf(o))){
            return String.valueOf(o);
        }
        return null;
    }
    @Override
    public void deleteUserByIds(String userIds) {
        this.removeByIds(Arrays.asList(userIds.split(",")));
    }

    @Override
    public Object getPageUserList(UserPage userPage) {
        Page<TSysDaUser> page=new Page<>(userPage.getPage().getPageNum(),userPage.getPage().getPageSize());
        QueryWrapper<TSysDaUser> wrapper = Wrappers.query();
        //组装查询条件
        if(StringUtils.isNotEmpty(userPage.getUser().getId())){
            wrapper.eq("ID",userPage.getUser().getId());
        }
        if(StringUtils.isNotEmpty(userPage.getUser().getLoginName())){
            wrapper.eq("LOGIN_NAME",userPage.getUser().getLoginName());
        }
        if(StringUtils.isNotEmpty(userPage.getUser().getUserName())){
            wrapper.like("USER_NAME",userPage.getUser().getUserName());
        }
        if(StringUtils.isNotEmpty(userPage.getUser().getSex())){
            wrapper.eq("SEX",userPage.getUser().getSex());
        }
        if(StringUtils.isNotEmpty(userPage.getUser().getEmail())){
            wrapper.like("EMAIL",userPage.getUser().getEmail());
        }
        if(StringUtils.isNotEmpty(userPage.getUser().getPhone())){
            wrapper.like("PHONE",userPage.getUser().getPhone());
        }
//        if(StringUtils.isNotEmpty(userPage.getUser().getOrgId())){
//            wrapper.eq("q.orgId",userPage.getUser().getOrgId());
//        }
//        if(StringUtils.isNotEmpty(userPage.getUser().getOrgName())){
//            wrapper.like("q.orgName",userPage.getUser().getOrgName());
//        }
        //
        if(StringUtils.isNotEmpty(userPage.getUser().getIsDefault())){
            wrapper.eq("q.isDefault",userPage.getUser().getIsDefault());
        }
        if(StringUtils.isNotEmpty(userPage.getUser().getUnitId())){
            wrapper.eq("UNIT_ID",userPage.getUser().getUnitId());
        }
        if(StringUtils.isNotEmpty(userPage.getUser().getUnitCode())){
            wrapper.eq("UNIT_CODE",userPage.getUser().getUnitCode());
        }
        if(StringUtils.isNotEmpty(userPage.getUser().getUnitName())){
            wrapper.like("UNIT_NAME",userPage.getUser().getUnitName());
        }
        if(StringUtils.isNotEmpty(userPage.getUser().getBaseId())){
            wrapper.eq("BASE_ID",userPage.getUser().getBaseId());
        }
        if(StringUtils.isNotEmpty(userPage.getUser().getBaseCode())){
            wrapper.eq("BASE_CODE",userPage.getUser().getBaseCode());
        }
        if(StringUtils.isNotEmpty(userPage.getUser().getBaseName())){
            wrapper.like("BASE_NAME",userPage.getUser().getBaseName());
        }

        wrapper.eq("STATUS", SbCode.DATA_NORMAL.getCode());
        wrapper.orderByDesc(" CREATE_TIME ");
        //list
        IPage<TSysDaUser> returnPage = userMapper.page(page, wrapper);
        //总数
        returnPage.setTotal(userMapper.count(wrapper));
        return returnPage;
    }

    @Override
    public void updateStausByIds(String ids) {
        QueryWrapper<TSysDaUser> wrapper = Wrappers.query();
        wrapper.in("ID",Arrays.asList(ids.split(",")));
        List<TSysDaUser> list = this.list(wrapper);
        List<TSysDaUser> updateBatchList = new ArrayList<>();
        for(TSysDaUser user : list){
            if(SbCode.DATA_NORMAL.getCode().equals(user.getStatus())){
                user.setStatus(SbCode.DATA_DISABLE.getCode());
            }else{
                user.setStatus(SbCode.DATA_NORMAL.getCode());
            }
//            this.updateById(user);
            updateBatchList.add(user);
        }
        if(updateBatchList.size() > 0 ){
            this.updateBatchById(updateBatchList);
        }
    }
}
